package com.bestescortbedsystem.shiro;

import com.bestescortbedsystem.entity.SesUser;
import com.bestescortbedsystem.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * ClassName: MyRealm
 * Package: com.bestescortbedsystem.shiro
 *
 * @author: guanzepeng
 * @Date: 2021/2/17 10:59 星期三
 * @Description: 自定义realm实现 将认证/授权数据来源转为数据库的实现
 */
@Slf4j
public class MyRealm extends AuthorizingRealm {

	@Resource
	private LoginService loginService;

	/**
	 * 授权方法
	 * @param principals
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

	/**
	 * 认证方法
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		log.info("开始认证!");
		//身份信息
		String principal = (String) token.getPrincipal();
		//调用查询方法
		SesUser sesUser = loginService.getFindByName(Long.valueOf(principal));

		//判定获取到的对象是否为空
		if(!ObjectUtils.isEmpty(sesUser)){
			return new SimpleAuthenticationInfo(sesUser.getUserphone(),sesUser.getUserpassword(),getName());
		}
		return null;
	}

	public static void main(String[] args) {
		Object obj = new SimpleHash("MD5","1","",1024);
		System.out.println(obj);
	}
}
